package com.biqee.crm.api.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.biqee.crm.api.TbTradeService;
import com.biqee.service.crm.CustomerService;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Trade;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.response.TradesSoldGetResponse;

public class TbTradeServiceImpl implements TbTradeService {
	
	private Log log = LogFactory.getLog(this.getClass());
	private String appkey = "12437492";

	private String apiUrl = "http://gw.api.tbsandbox.com/router/rest";

	private String secret = "sandbox425fc15cff43fad2426c60bf1";
	
	private long  threeMonthTimeMills = 3*30*24*60*60*1000L;
	
	private CustomerService customerService ;

	private String fileds = "seller_nick, buyer_nick, title, type, created, tid, seller_rate," +
			" buyer_rate, status, payment, discount_fee, adjust_fee, post_fee, total_fee, pay_time," +
			" end_time, modified, consign_time, buyer_obtain_point_fee, point_fee, real_point_fee," +
			" received_payment, commission_fee, pic_path, num_iid, num, price, cod_fee, cod_status, " +
			"shipping_type, receiver_name, receiver_state, receiver_city, receiver_district, receiver_address," +
			" receiver_zip, receiver_mobile, receiver_phone,seller_flag";

	/**
	 * @param userSessionKey
	 *            沙箱获取方式， 访问
	 *            http://container.api.tbsandbox.com/container?appkey=12437492
	 * 
	 * 
	 */
	@Override
	public void getTradeData(Long userId,String userSessionKey) {
		TaobaoClient client = new DefaultTaobaoClient(apiUrl, appkey, secret);
		TradesSoldGetRequest req = new TradesSoldGetRequest();
		req.setFields(fileds);
		Date dateTime = new Date(new Date().getTime()-threeMonthTimeMills);
		req.setStartCreated(dateTime);
		req.setEndCreated(new Date());
		req.setPageNo(1L);
		req.setPageSize(100L);
		try {
			TradesSoldGetResponse response = client
					.execute(req, userSessionKey);
			if(response.isSuccess()){
				List<Trade>  tradeList = response.getTrades();
				customerService.importTrade(userId, tradeList);
			}else{
				log.error("error code:"+response.getErrorCode()+","+response.getMsg()+",\r\nsubcode:"+
						response.getSubCode()+","+response.getSubMsg());
			}
		} catch (ApiException e) {
			log.error( e.getMessage(),e);
		}

	}

	public String getAppkey() {
		return appkey;
	}

	public void setAppkey(String appkey) {
		this.appkey = appkey;
	}

	public String getApiUrl() {
		return apiUrl;
	}

	public void setApiUrl(String apiUrl) {
		this.apiUrl = apiUrl;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}
	
}
